package com.luzhikun.jsptest.myjsp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: StudentsIDao
 * Description:
 * date: 2021/4/27 12:30
 *
 * @author luzhikun
 * @since JDK 1.8
 */
public class StudentsIDao {
    /**
     * 查询学生
     */

    public List<Students> getStudent(String name) {
        if (name == null) {
            name = "";
        }
        List<Students> list = null;
        //创建连接对象
        Connection conn = null;
        //创建预操作对象
        PreparedStatement pst = null;
        //创建结果集
        ResultSet rs = null;
        //创建连接
        conn = DBCPUtil.getConnection();
        //编写sql
        String sql = "select * from t_student where t_name like ? ";
        //编译sql
        try {
            pst = conn.prepareStatement(sql);
            //动态替换占位符
            pst.setString(1, "%" + name + "%");

            //获取结果集
            rs = pst.executeQuery();
//            System.out.println("吴杰是狗");
            //解析结果集
//            if (rs!=null && rs.next()){
            if (rs != null) {
                list = new ArrayList<>();
//                System.out.println("吴杰真的狗");
                while (rs.next()) {
                    Students students = new Students();
                    students.setId(rs.getInt("t_id"));
                    students.setName(rs.getString("t_name"));
                    students.setSex(rs.getString("sex"));
                    students.setAge(rs.getInt("age"));
                    list.add(students);
//                    System.out.println("吴杰狗");
                }

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } //关闭操作
        finally {
            DBCPUtil.closeAll(rs, pst, conn);
        }

        return list;
    }
}
